#pragma strict
//////////////////////////////////////////////////////
///一个下载组件,下载时附加到GameObject
//////////////////////////////////////////////////////
/** www */
// private var www:WWW;
/** loading function */
private var progressFun:Function;


/** 下载场景. */
function LoadLevel(url:String,version:int,onOk:Function){
	if(String.IsNullOrEmpty(url)){
		Debug.LogError("url? "+url);
		return;
	}
	var www:WWW = Setup(url,version);
	yield WaitForLoading(www);
	//构件场景.
	var ab:AssetBundle = www.assetBundle;
	if(onOk != null){
		onOk();
	}
}

/**新建WWW
	载入素材
	@param url
	@param version,为-1时,不从缓存载入.
	@param onOk : function(prefab:Game):void
*/
function Load(url:String,version:int,onOk:Function){
	yield Load(url,version,onOk,null);
}
/** 载入素材 */
function Load(url:String,version:int,onOk:Function,onProgress:Function){
	var ab:AssetBundle = null;
	//检查是否已经被销毁.
	AssetBundleDictionary.RemoveInvalid(url);
	//检查是否已经存在.
	if(! AssetBundleDictionary.Contains(url)){
		var www:WWW = Setup(url,version);
		if(onProgress != null)
			progressFun = onProgress;
		yield WaitForLoading(www);
		//再次查看是否已经被缓存.
		if(! AssetBundleDictionary.Contains(url)){
			ab = www.assetBundle;
			AssetBundleDictionary.Add(url,ab);
		}
	}
	if(! ab){
		ab = AssetBundleDictionary.Get(url);
	}
	onOk(ab);
}
/**新建WWW,载入文本.*/
function LoadText(url:String,onOk:Function){
	var www:WWW = WWW(url);
	yield WaitForLoading(www);
	onOk(www.text);
}
/**新建WWW,载入字节 */
function LoadBytes(url:String,version:int,onOk:Function){
	var www:WWW = WWW(url);
	yield WaitForLoading(www);
	onOk(www.bytes);
}

/**等待完成.*/
protected function WaitForLoading(www:WWW){
	while(! www.isDone){
		if(www.error){
			Debug.Log(www.error + "=>"+ www.url);
			break;
		}
		if(progressFun)
			progressFun(www.progress);
		yield;
	}
}
/** 准备 */
protected function Setup(url:String,version:int){
	var www:WWW;
	if(version == -1){
		www = WWW(url);
	}else{
		www = WWW.LoadFromCacheOrDownload(url,version);
	}
	Debug.Log("准备下载:"+url);
	return www;
}